package com.gec.teams.wechat.mongodb;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import com.gec.teams.wechat.pojo.entity.MessageEntity;
import com.gec.teams.wechat.pojo.entity.MessageRefEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 功能：
 * 作者：YumTea
 * 日期：2024/6/25 9:32
 */
@Repository
public class MessageDao {
    //注入MongoDB控制类
    @Autowired
    private MongoTemplate mongoTemplate;

    public String insert(MessageEntity message){
        //传入的北京时间取出
        Date sendTime = message.getSendTime();
        //设置为格林时间？
        DateUtil.offset(sendTime, DateField.HOUR,8);
        message.setSendTime(sendTime);
          message= mongoTemplate.save(message);
        return message.get_id();
    }
    //分页查询消息
    public List<HashMap> searchMessageByPage(int userId, long start, int length){
        //查询 message_ref 里 userID 对应的messageId 判断是不是已读
//        LookupOperation lookupOperation=LookupOperation.newLookup().
//                from("message_ref").  //关联从表名
//                        localField("id").     //主表关联字段
//                        foreignField("messageId").//从表关联的字段
//                        as("Reslut");   //查询结果名
//带条件查询可以选择添加下面的条件
//       Criteria criteria=Criteria.where("studenAndgrade").not().size(0);   //只查询有结果的学生
//        Criteria qqq=Criteria.where("name").regex("文");//只查询名字中带有文的
//               AggregationOperation match1= Aggregation.match(qqq);
//        AggregationOperation match = Aggregation.match(criteria);
//        Aggregation counts = Aggregation.newAggregation(match1,lookupOperation,match).;
//        Aggregation aggregation= Aggregation.newAggregation(lookupOperation);
//        List<HashMap> results = mongoTemplate.aggregate(aggregation,"message", HashMap.class).getMappedResults();
//        //上面的student必须是查询的主表名
//        System.out.println(results.toString());


        JSONObject json = new JSONObject();
        //把id转化为String类型
        json.set("$toString","$_id");
        Aggregation aggregation = Aggregation.newAggregation(
                //先执行我们的id类型转换
                Aggregation.addFields().addField("id").withValue(json).build(),
                //参数分别是，从表名，主表关联字段，从表关联字段，查询结果名
                Aggregation.lookup("message_ref","id","messageId","ref"),
                //添加查询条件,ref中的接收人员的id(receiverId)等于userId
                Aggregation.match(Criteria.where("ref.receiverId").is(userId)),
                //添加排序
                Aggregation.sort(Sort.by(Sort.Direction.DESC, "sendTime")),
                //MongoDb是从0开始
                Aggregation.skip(start),
                Aggregation.limit(length)
        );
        //执行语句，第一个类似于构造器吧，然后是主表，然后是返回类型
        AggregationResults<HashMap> results = mongoTemplate.aggregate(aggregation, "message", HashMap.class);
        List<HashMap> list = results.getMappedResults();
        //开始分组，进行数据处理
        list.forEach(one->{
            List<MessageRefEntity> refList= (List<MessageRefEntity>) one.get("ref");
            MessageRefEntity entity=refList.get(0);
            boolean readFlag=entity.getReadFlag();
            String refId=entity.get_id();
            one.put("readFlag",readFlag);
            one.put("refId",refId);
            one.remove("ref");
            one.remove("_id");
            Date sendTime= (Date) one.get("sendTime");
            sendTime=DateUtil.offset(sendTime,DateField.HOUR,-8);

            String today=DateUtil.today();
            //如果消息是当天发出的只显示时间,如果是之前发出的要显示年月日
            if(today.equals(DateUtil.date(sendTime).toDateStr())){
                one.put("sendTime",DateUtil.format(sendTime,"HH:mm"));
            }
            else{
                one.put("sendTime",DateUtil.format(sendTime,"yyyy/MM/dd"));
            }
        });
        return list;
    }


    //根据消息id查询消息
    public HashMap searchMessageById(String id){
        HashMap message = mongoTemplate.findById(id, HashMap.class, "message");
        Date sendTime = (Date) message.get("sendTime");
        sendTime=DateUtil.offsetHour(sendTime,-8);
        //这个是替换
        message.replace("sendTime",DateUtil.format(sendTime,"yyyy-MM-dd HH:mm"));
        return message;
    }
}
